<?php
namespace application\utilities;

class Utility {
	
	public static function reportToConsole($report) {
		global $concerto;
		$currentUrl = str_replace(CN_URL, '', $concerto->UrlInterpreter->currentUrl);
		$console = CN_APPLICATION_PATH."console.txt";
		$fh = fopen($console, 'a') or die("can't open file");
		$stringData = "\n[".date("h:i:s m/d/Y", time()) . " ".$currentUrl."]: ".$report;
		fwrite($fh, $stringData);
		
		fclose($fh);
	}
	
	public static function sqlImplodedArray($array) {
		if(is_array($array)) {
			return "'".implode("', '", $array)."'";
		}
		return FALSE;
	}
	
	public static function objectify($array) {
		foreach($array as $key=>$value) {
			if(is_array($value)) {
				$array[$key] = self::objectify($value);
			}
		}
		
		return (object) $array;
	}
	
	public static function arrayFunction($array, $function) {
		foreach($array as $key=>$value) {
			if(is_array($value)) {
				$array[$key] = self::arrayFunction($value, $function);
			}
			elseif(is_object($value)) {
				$array[$key] = (object)self::arrayFunction((array)$value, $function);
			}
			else {
				$array[$key] = $function($value);
			}
		}
		
		return $array;
	}
	
	public static function triggerError($error) {
		trigger_error($error, E_USER_ERROR);
	}
	
	// Returns the # of seconds since UNIX epoch of the date
	public static function checkDate($date) {
		if(is_numeric($date)) return $date;
		else return strtotime($date);
	}
	
	public static function toCamelCase($string) {
		$string = str_replace(' ', '_', $string);
		if(strpos($string, '_') !== FALSE) {
			$string = explode('_', $string);
			$count = count($string);
			$return = strtolower($string[0]);
			for($i=1;$i<$count;$i++) {
				$return .= strtoupper($string[$i][0]).strtolower(substr($string[$i], 1));
			}
			return $return;
		}
		return $string;
		
		
	}
	
	public static function toUpperCamelCase($string) {
		$string = str_replace(' ', '_', $string);
		if(strpos($string, '_') !== FALSE) {
			$string = explode('_', $string);
			$count = count($string);
			$return = '';
			for($i=0;$i<$count;$i++) {
				$return .= strtoupper($string[$i][0]).strtolower(substr($string[$i], 1));
			}
			return $return;
		}
		else {
			return ucwords($string);
		}		
		return $string;
	}
	
	public static function toSqlCase($string) {
		$string = preg_replace('/([A-Z])/', '_$1', $string);
		return strtolower($string);
	}
	
	public static function camelCaseToNormal($string) {
		$first = $string[0];
		$string = substr($string, 1);
		$string = preg_replace('/([A-Z])/', ' $1', $string);
		return $first.$string;
	}
	
	public static function makeUrl($url) {
		$name = strtolower($url);
		$name = preg_replace('/[^0-9A-Za-z\s+_-]/', '', $name);
		$name = preg_replace('/\s+/', '-', $name);
		return $name;
	}
	
	public static function makeColumn($name) {
		$name = strtolower($name);
		$name = preg_replace('/[^0-9A-Za-z\s+_-]/', '', $name);
		$name = preg_replace('/\s+/', '_', $name);
		return $name;
	}
	
	public static function makeUnique($string, $array) {
		$i = 1;
		$unique = $string;
		while(in_array($unique, $array)) {
			$unique = $string.$i;
			$i++;
		}
		return $unique;
	}
	
	public static function makeUniqueUrl($string) {
		$url = self::makeUrl($string);
		$urls = DB()->getVarArray("SELECT `content_permalink` FROM `cn_content`");
		$urls = array_merge($urls, DB()->getVarArray("SELECT `tag_permalink` FROM `cn_tags`"));
		$urls = array_merge($urls, DB()->getVarArray("SELECT `ct_permalink` FROM `cn_content_types`"));
		$unique = Utility::makeUnique($url, $urls);
		return $unique;
	}
	
	/**
	 * strposall
	 *
	 * Find all occurrences of a needle in a haystack
	 *
	 * @param string $haystack
	 * @param string $needle
	 * @return array or false
	 */
	public static function strposall($haystack,$needle) {
	   
	    $s=0;
	    $i=0;
	   
	    while (is_integer($i)){
	       
	        $i = strpos($haystack,$needle,$s);
	       
	        if (is_integer($i)) {
	            $aStrPos[] = $i;
	            $s = $i+strlen($needle);
	        }
	    }
	    if (isset($aStrPos)) {
	        return $aStrPos;
	    }
	    else {
	        return false;
	    }
	}
	
	/**
	 * Generate and return a random string
	 *
	 * The default string returned is 8 alphanumeric characters.
	 *
	 * The type of string returned can be changed with the "seeds" parameter.
	 * Four types are - by default - available: alpha, numeric, alphanum and hexidec. 
	 *
	 * If the "seeds" parameter does not match one of the above, then the string
	 * supplied is used.
	 *
	 * @author      Aidan Lister <aidan@php.net>
	 * @version     2.1.0
	 * @link        http://aidanlister.com/repos/v/function.str_rand.php
	 * @param       int     $length  Length of string to be generated
	 * @param       string  $seeds   Seeds string should be generated from
	 */
	public static function strRand($length = 8, $seeds = 'alphanum') {
	    // Possible seeds
	    $seedings['alpha'] = 'abcdefghijklmnopqrstuvwqyz';
	    $seedings['numeric'] = '0123456789';
	    $seedings['alphanum'] = 'abcdefghijklmnopqrstuvwqyz0123456789';
	    $seedings['hexidec'] = '0123456789abcdef';
	    
	    // Choose seed
	    if (isset($seedings[$seeds]))
	    {
	        $seeds = $seedings[$seeds];
	    }
	    
	    // Seed generator
	    list($usec, $sec) = explode(' ', microtime());
	    $seed = (float) $sec + ((float) $usec * 100000);
	    mt_srand($seed);
	    
	    // Generate
	    $str = '';
	    $seeds_count = strlen($seeds);
	    
	    for ($i = 0; $length > $i; $i++)
	    {
	        $str .= $seeds{mt_rand(0, $seeds_count - 1)};
	    }
	    
	    return $str;
	}
	
	/**
	 * Removes a value from an array
	 *
	 * @param array $array The array to remove the value from
	 * @param mixed $value The value to remove
	 */
	public static function arrayRemoveValue ($array, $value) {
		$key = array_search($value, $array);
		if($key !== FALSE) unset($array[$key]);
		return $array;
	}
	
	
}

?>